<?php

namespace App\Http\Controllers\Contract;

use App\Helpers\ContractApiTrait;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\SystemLog;
use Illuminate\Http\Request;
use App\Models\Contract\CarContract;
use Modules\Car\Entities\CarOrder;

class ContractCallbackController extends Controller
{
    use ResponseData, ContractApiTrait;

    //'templateId'=>'yDCDxUUndn7miqUJE1yYEGB0yQNH4OBw'
    public function contractCallback(Request $request){
        $this->callbackLog($request);
        if($request->input('msgData.flowId') && $request->input('msgData.flowStatus')){
            $contract=CarContract::where('flow_id',$request->input('msgData.flowId'))->first();
            if($contract){
                $contract->flow_status = $request->input('msgData.flowStatus');
                // 合同撤销后软删除本地合同数据
                if($request->input('msgData.flowStatus')=='CANCEL'){
                    $contract->deleted_at = now();
                }
                // 合同签署完成后，订单自动进入用车中
                if($request->input('msgData.flowStatus')=='ALL'){
                    CarOrder::where('id',$contract->order_id)->where('status','>',0)->update(['is_sign_contract'=>3]);
                }
                // 如果合同过期了，订单状态待签署变更为待送达
                if($request->input('msgData.flowStatus')=='DEADLINE'){
                    CarOrder::where('id',$contract->order_id)->where('status','>',0)->update(['status'=>5,'is_sign_contract'=>0,'process_status'=>1]);
                }
                $contract->save(); 
            }else{
                CarContract::where('flow_id',$request->input('msgData.flowId'))
                    ->update(['flow_status'=>$request->input('msgData.flowStatus')]);
            }
        }

        return $this->message('success');
    }
    //
    public function callbackLog($request)
    {
        SystemLog::create([
            'type'=>'contract_callback',
            'info'=>$request->getContent(),
            'param'=>json_encode($request->all()),
            'extra'=>$request->user()->id??'',
        ]);
    }


}
